//
//  UITextView+extension.swift
//  测试-表情键盘
//
//  Created by shmily on 15/8/7.
//  Copyright © 2015年 shmilyAshen. All rights reserved.
//

import UIKit

extension UITextView {
    
    /// 将文本添加到 tetxView 中
    func insertEmoticon(emoticon: Emoticon) {
        if let emoji = emoticon.emoji {
            replaceRange(selectedTextRange!, withText: emoji)
            return
        }
        
        let attach = EmoticonAttachment()
        attach.image = UIImage(contentsOfFile: emoticon.imagePath)
        attach.chs = emoticon.chs
        attach.bounds = CGRect(x: 0, y: -4, width: 32, height: 32)
        
        let textImage = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attach))
        
        /// 添加属性
        textImage.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
        
        /// 获取文本框的内容,转换为 attributeString
        let text = NSMutableAttributedString(attributedString: attributedText)
        
        let range = selectedRange
        /// 添加字符串
        
        text.replaceCharactersInRange(selectedRange, withAttributedString: textImage)
        //赋值文本
        attributedText = text as NSAttributedString
        //设置到选中的位置
        selectedRange = NSMakeRange(range.location + 1, 0)
    }
    
    // 对属性文本进行检测，并且拼接返回一个字符串
    /// 计算型属性，返回完整字符串
    var emoticonText: String {
        
        // 属性文本是分段保存的，能否把每一个分段拿到
        let attrString = attributedText
        var strM = String()
        
        attrString.enumerateAttributesInRange(NSMakeRange(0, attrString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                    strM += attachment.chs!
            } else {
                // 使用 range 获取文本内容
                let str = (attrString.string as NSString).substringWithRange(range)
                strM += str
            }
        }
        return strM
    }

    
}